#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
import time

import FileHostProtoType

class fciitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class filecloud(FileHostProtoType.FileHostProcess):  
    LOGIN_URL = "https://secure.filecloud.io/user-login_p.html"
    ACCOUNT_URL = "https://secure.filecloud.io/user-account.html"
    UPLOAD_PAGE_URL = "http://filecloud.io/upload.html"
              
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "FileCloud.io" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.logtype = 'poster'
        self.apikey = ''
        
        self._cookieCurl = self._user + '_%s.cookie' % self.hostname
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
            
    def login(self):
#        if self.islogin:
#            return True
        #build opener
        self.generateOpener()
        if self.restore_cookiejar():
            return True
        self.fherr.write('login to %s %s/%s...'%(self.hostname, self._user,'*'*len(self._pwd)))
        loginData = {'username' : self._user, \
                'password' : self._pwd}
        response = self.loginFileHost(self.LOGIN_URL, loginData)
        
        if "reCaptcha" in response:
            self.fherr.write("You login too often, need to input reCaptcha -_,-.")
            return False
        # check
        cookie_status = self.check_cookie()
        if not cookie_status:
            self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
            self.fherr.write(response)
            return False
        self.fherr.write('write cookie file.')
        try:
            os.remove(self._cookieCurl)
        except:
            self.fherr.write('Exception occured when deling Local Cookie.')
        self._cj.save(self._cookieCurl, ignore_discard=True)
        return True   

    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(self._cookieCurl, ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to conferm cookie is avaiable
            return self.check_cookie()
        return False
    
    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request(self.ACCOUNT_URL, retry=1)
        if response and self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        # self.fherr.write(response)
        return False
            
    def getFileList(self):
        return []
    
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        #indexpage        
        get_upload_info_page = self.post_request(self.UPLOAD_PAGE_URL)
        
        upload_url = self.get_upload_key(get_upload_info_page, 'var __upload_url', 1, "'")
               
        self.apikey = self.get_upload_key(get_upload_info_page, 'akey', -2, "'")
        info = "Uploading...%s" % file
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
            
        fileobj = open(file, 'rb')
        fileobj.seek(start_point)  
        
        data = {"akey":self.apikey,
                "Filedata":fileobj}
        
        self.fherr.write(info)
        self.fherr.write("Apikey:{}\r\nUpload_url:{}".format(self.apikey, upload_url))
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_request(upload_url, \
                                   data, \
                                   cb=callback, \
                                   retry=1, \
                                   setfilename=filename, \
                                   setfilesize=filesize)
        #result
        self.fherr.write(result)
        content = json.loads(result)
        if content['status'] == 'error':
            self.fherr.write("Get a wrong result after uploaded.")
            self.fherr.write(content['message'])
            return
        
        link = 'http://filecloud.io/{ukey}/{name}'.format(**content)
        item = fciitem(os.path.basename(file), 'file', '', link, filename)
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        return item